package cn.guyouda.algorithms;

import org.junit.Test;

/**
 * 基于Java实现的单向链表
 *
 * @author Youda
 */
public class LinkedList {

    @Test
    public void test1() {
        Node<String> node1 = new Node<>();
        Node<String> node2 = new Node<>();
        Node<String> node3 = new Node<>();

        node1.item = "First";
        node2.item = "Second";
        node3.item = "Third";

        node1.next = node2;
        node2.next = node3;

        Node<String> node = node1;
        while (true) {
            System.out.println(node.item);
            if (node.next != null) {
                node = node.next;
            } else {
                break;
            }

        }
    }

    @Test
    public void testAdd() {

        Node<String> node1 = new Node<>();
        Node<String> node2 = new Node<>();
        Node<String> node3 = new Node<>();

        node1.item = "First";
        node2.item = "Second";
        node3.item = "Third";

        node1.next = node2;
        node2.next = node3;

        Node<String> newNode = new Node<>();
        newNode.item = "NewNode";
        newNode.next = node1;

        Node<String> node = newNode;
        while (true) {
            System.out.println(node.item);
            if (node.next != null) {
                node = node.next;
            } else {
                break;
            }

        }

    }


    /**
     * 自定义链表节点
     *
     * @param <Item> 节点值
     */
    private class Node<Item> {
        Item item;// 节点值
        Node next;//下一节点的引用，若没有下一节点，则为null

    }

}
